package com.kbbywyclient.ui.activity;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.kbbywyclient.R;
import com.kbbywyclient.data.entity.Event;
import com.kbbywyclient.data.entity.LoansTableMenu;
import com.kbbywyclient.data.entity.ResultInfo;
import com.kbbywyclient.data.entity.TabledBuy;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.ProductTableModule;
import com.kbbywyclient.presenter.ProductTablePresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.adapter.MenuCreditCardAdapter;
import com.kbbywyclient.ui.adapter.MenuProductAdapter;
import com.kbbywyclient.ui.adapter.MenuProfessionAdapter;
import com.kbbywyclient.ui.adapter.ProductTableAdapter;
import com.kbbywyclient.ui.contarct.ProductTableContract;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.ViewUtils;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomDialog;
import com.kbbywyclient.widget.CustomPopwin;
import com.kbbywyclient.widget.CustomToolBar;
import com.kbbywyclient.widget.GetMoreListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;

/**
 * Description:
 * Created by FHW
 * on 2017/4/11
 */

public class ProductTableActivity extends BaseActivity implements ProductTableContract.View {

    @BindView(R.id.v_toolbar)
    CustomToolBar v_toolbar;
    @BindView(R.id.ptr_view)
    PtrClassicFrameLayout ptr_view;
    @BindView(R.id.lv_product_table)
    GetMoreListView lv_product_table;

    @BindView(R.id.ll_view)
    LinearLayout ll_view;
    @BindView(R.id.ll_toolbar)
    LinearLayout ll_toolbar;
    @BindView(R.id.tv_purpose)
    TextView tv_purpose;
    @BindView(R.id.tv_profession_info)
    TextView tv_profession_info;
    @BindView(R.id.tv_card_holding)
    TextView tv_card_holding;
    @BindView(R.id.iv_purpose)
    ImageView iv_purpose;
    @BindView(R.id.iv_profession_info)
    ImageView iv_profession_info;
    @BindView(R.id.iv_card_holding)
    ImageView iv_card_holding;

    @Inject
    ProductTablePresenter productTablePresenter;

    private String CompanyID = "";
    private String CompanyTypeID = "";
    private String loansType = "0";//贷款类型
    private String workTypeCode = "";//职业身份码表
    private String productLoansID = "0";//指定受理贷款产品ID
    private String houseId = "";//房产ID集 ,多选用逗号隔开
    private String creditCard = "";//是否有信用卡1是0否
    private String carID = "";//车ID集 ,多选用逗号隔开
    private String credit = "";//两年内信用ID集 ,多选用逗号隔开
    private String monthlyIncome = "";//MonthlyIncome 工资/月ID集 可选,注意,因为"上班族和无固定职业"都同样有这个选项,前台取码表时,选中一个时要两个对应的都传过来.月收入ID集 ,多选用逗号隔开
    private int applyStarDateTime = 0;//时间段开始，int时间戳
    private int applyEndDateTime = 0;//时间段结束，int时间戳

    private ProductTableAdapter productTableAdapter = null;

    private int mType = -1;//0-贷款用途 1-职业信息 2-持卡情况

    private CustomPopwin popwin;//

    private boolean isFirstLoad = true;

    private List<LoansTableMenu.ProductListBean> productList = null;//贷款产品
    private MenuProductAdapter menuProductAdapter = null;

    private List<LoansTableMenu.WorkTypeListBean> workTypeList = null;
    private MenuProfessionAdapter menuProfessionAdapter = null;

    private List<LoansTableMenu.CreditCardBean> creditCardBeanList = null;
    private MenuCreditCardAdapter menuCreditCardAdapter = null;

    private List<ResultInfo> resultInfoList = null;

    private int applyLoansID = -1;
    private String applyLoansSN = "";
    private int mPosition = 0;

    private CustomDialog dialog;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_product_table;
    }

    @OnClick({R.id.ll_purpose, R.id.ll_profession_info, R.id.ll_card_holding})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_purpose://贷款产品
                mType = 0;
                showView(mType);
                showPop(view);
                if (!isFirstLoad && productList.size() < 0) {
                    productTablePresenter.getloansOrdersMenu(PreUtils.getUser(this).getSalesID() + "");
                }
                break;
            case R.id.ll_profession_info://职业信息
                mType = 1;
                showView(mType);
                showPop(view);
                if (!isFirstLoad && workTypeList.size() < 0) {
                    productTablePresenter.getloansOrdersMenu(PreUtils.getUser(this).getSalesID() + "");
                }
                break;
            case R.id.ll_card_holding://持卡情况
                mType = 2;
                showView(mType);
                showPop(view);
                if (!isFirstLoad && creditCardBeanList.size() < 0) {
                    productTablePresenter.getloansOrdersMenu(PreUtils.getUser(this).getSalesID() + "");
                }
                break;
        }
    }

    private void showPop(View view) {
        View proView = LayoutInflater.from(this).inflate(R.layout.pop_product_table, null, false);
        ListView lv_purpose = (ListView) proView.findViewById(R.id.lv_purpose);
        ListView lv_profession_info = (ListView) proView.findViewById(R.id.lv_profession_info);
        ListView lv_card_holding = (ListView) proView.findViewById(R.id.lv_card_holding);

        View v_dimess = proView.findViewById(R.id.v_dimess);

        lv_purpose.setVisibility(View.GONE);
        lv_profession_info.setVisibility(View.GONE);
        lv_card_holding.setVisibility(View.GONE);

        //获取popupwindow高度确定动画开始位置
//        int contentHeight = PopUtils.getViewMeasuredHeight(proView);

        if (popwin == null) {
            popwin = new CustomPopwin(this, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1.0f);
        }
        switch (mType) {
            case 0:
                lv_purpose.setVisibility(View.VISIBLE);
                if (productList != null) {
                    setProductAdapter(lv_purpose);
                }
                break;
            case 1:
                lv_profession_info.setVisibility(View.VISIBLE);
                if (workTypeList != null) {
                    setProfessionAdapter(lv_profession_info);
                }
                break;
            case 2:
                lv_card_holding.setVisibility(View.VISIBLE);
                if (creditCardBeanList != null) {
                    setCreditCardAdapter(lv_card_holding);
                }
                break;
        }
        popwin.setFocusable(false);
        popwin.setContentView(proView);
        popwin.showAsDropDown(view, 0, 0);

        popwin.setOnDismissListener(() -> {
            setTextType();
        });
        lv_purpose.setOnItemClickListener((parent, view1, position, id) -> {
            popwin.dismiss();
            for (int i = 0; i < productList.size(); i++) {
                productList.get(i).setCheck(false);
                if (position == i) {
                    productList.get(i).setCheck(true);
                    productLoansID = productList.get(i).getID() + "";
                    ViewUtils.setText(tv_purpose, productList.get(i).getName());
                }
            }
            ptr_view.autoRefresh();
        });
        lv_profession_info.setOnItemClickListener((parent, view12, position, id) -> {
            popwin.dismiss();
            for (int i = 0; i < workTypeList.size(); i++) {
                workTypeList.get(i).setCheck(false);
                if (position == i) {
                    workTypeList.get(i).setCheck(true);
                    workTypeCode = workTypeList.get(i).getCode();
                    ViewUtils.setText(tv_profession_info, workTypeList.get(i).getName());
                }
            }
            ptr_view.autoRefresh();
        });
        lv_card_holding.setOnItemClickListener((parent, view13, position, id) -> {
            popwin.dismiss();
            for (int i = 0; i < creditCardBeanList.size(); i++) {
                creditCardBeanList.get(i).setCheck(false);
                if (position == i) {
                    creditCardBeanList.get(i).setCheck(true);
                    creditCard = creditCardBeanList.get(i).getCode();
                    ViewUtils.setText(tv_card_holding, creditCardBeanList.get(i).getName());
                }
            }
            ptr_view.autoRefresh();
        });

        v_dimess.setOnClickListener(v -> popwin.dismiss());

    }

    /**
     * 设置贷款用途 菜单数据
     *
     * @param lv
     */
    private void setProductAdapter(ListView lv) {
        menuProductAdapter = new MenuProductAdapter(this, R.layout.item_menu_purpose, productList);
        lv.setAdapter(menuProductAdapter);
    }

    private void setProfessionAdapter(ListView lv) {
        menuProfessionAdapter = new MenuProfessionAdapter(this, R.layout.item_menu_purpose, workTypeList);
        lv.setAdapter(menuProfessionAdapter);
    }

    private void setCreditCardAdapter(ListView lv) {
        menuCreditCardAdapter = new MenuCreditCardAdapter(this, R.layout.item_menu_purpose, creditCardBeanList);
        lv.setAdapter(menuCreditCardAdapter);
    }

    private void showView(int type) {
        setTextType();
        switch (type) {
            case 0:
                tv_purpose.setTextColor(getResources().getColor(R.color.color_14C095));
                iv_purpose.setBackgroundResource(R.mipmap.icon_table_up);
                break;
            case 1:
                tv_profession_info.setTextColor(getResources().getColor(R.color.color_14C095));
                iv_profession_info.setBackgroundResource(R.mipmap.icon_table_up);
                break;
            case 2:
                tv_card_holding.setTextColor(getResources().getColor(R.color.color_14C095));
                iv_card_holding.setBackgroundResource(R.mipmap.icon_table_up);
                break;
        }
    }

    private void setTextType() {
        tv_purpose.setTextColor(getResources().getColor(R.color.color_212121));
        tv_profession_info.setTextColor(getResources().getColor(R.color.color_212121));
        tv_card_holding.setTextColor(getResources().getColor(R.color.color_212121));
        iv_purpose.setBackgroundResource(R.mipmap.icon_table_dwon);
        iv_profession_info.setBackgroundResource(R.mipmap.icon_table_dwon);
        iv_card_holding.setBackgroundResource(R.mipmap.icon_table_dwon);
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("贷款-产品申请表");
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);

        resultInfoList = new ArrayList<>();

        productList = new ArrayList<>();
        workTypeList = new ArrayList<>();
        creditCardBeanList = new ArrayList<>();

        CompanyID = getIntent().getStringExtra("CompanyID");
        CompanyTypeID = getIntent().getStringExtra("CompanyTypeID");

        v_toolbar.setLeftViewOnClickLinster(v -> finish());
        v_toolbar.setRightViewOnClickLinster(v -> {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("type", 1);
            ActivitySkipUtil.skipAnotherActivity(this, DiscountActivity.class, map);
        });

        //加载更多
        lv_product_table.setOnGetMoreListener(() -> {
            refresh(false);
        });
        lv_product_table.setOnItemClickListener((parent, view, position, id) -> {
            if (position < resultInfoList.size() && resultInfoList.size() > 0) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("ApplyLoansID", resultInfoList.get(position).getApplyLoansID());
                map.put("ApplyLoansSN", resultInfoList.get(position).getApplyLoansSN());
                map.put("position", position);
                //贷款产品申请表大数据埋点
                Map<String,String> bigDataMap = new HashMap<>();
                bigDataMap.put("page","贷款业务");
                bigDataMap.put("order_id",String.valueOf(applyLoansID));
                bigDataMap.put("order_name",applyLoansSN);
                bigDataMap.put("behavior","cbeibei_loan_product_click");
                productTablePresenter.bigDataBuried(bigDataMap);
                ActivitySkipUtil.skipAnotherActivity(this, LoansTableDetailActivity.class, map);
            }
        });

        lv_product_table.setOnSileListener(new GetMoreListView.OnSileListener() {
            @Override
            public void onSlideUp(int direction) {
                ll_view.setVisibility(View.GONE);
                ViewUtils.setViewAnim(direction, ll_toolbar);
            }

            @Override
            public void onSlideDwon(int direction) {
                ll_view.setVisibility(View.INVISIBLE);
                ViewUtils.setViewAnim(direction, ll_toolbar);
            }
        });

    }

    @Override
    public void initData() {
        ptr_view.setLastUpdateTimeRelateObject(this);
        ptr_view.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                lv_product_table.setHasMore();
                refresh(true);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
        // the following are default settings
        ptr_view.setResistance(1.7f);
        ptr_view.setRatioOfHeaderHeightToRefresh(1.2f);
        ptr_view.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptr_view.autoRefresh();
            }
        }, 100);
    }


    private void refresh(boolean isClean) {
        productTablePresenter.getProductOrderLoans(isClean, PreUtils.getUser(this).getSalesID() + "", PreUtils.getUser(this).getCity() + ""
                , loansType, workTypeCode, productLoansID, creditCard, houseId, carID, credit, monthlyIncome, applyStarDateTime, applyEndDateTime);
    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getProductTableComponent(new ProductTableModule(this)).inject(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 购买 回调
     *
     * @param notifyCustomerTable
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event.NotifyCustomerTable notifyCustomerTable) {
        resultInfoList.remove(notifyCustomerTable.getPosition());
        productTableAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event.LoansTableBuy loansTableBuy) {
        applyLoansID = resultInfoList.get(loansTableBuy.getPosition()).getApplyLoansID();
        applyLoansSN = resultInfoList.get(loansTableBuy.getPosition()).getApplyLoansSN();
        mPosition = loansTableBuy.getPosition();
        productTablePresenter.getApplyLoansBuyy(PreUtils.getUser(ProductTableActivity.this).getSalesID() + ""
                , applyLoansID + "", applyLoansSN, ""
                , "1");
    }

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    @Override
    public void loadSucProductTable(List<ResultInfo> resultInfoList) {
        ptr_view.refreshComplete();
        if (isFirstLoad) {
            ll_view.setVisibility(View.INVISIBLE);
            productTablePresenter.getloansOrdersMenu(PreUtils.getUser(this).getSalesID() + "");
        }
    }

    @Override
    public void loadFaiProductTable(String errorMsg) {
        ptr_view.refreshComplete();
        lv_product_table.getMoreComplete();
    }

    @Override
    public void setAdapterOrNotify(List<ResultInfo> mResultInfoList) {
        if (resultInfoList.size() > 0) {
            resultInfoList.clear();
        }
        resultInfoList.addAll(mResultInfoList);
        if (productTableAdapter == null) {
            productTableAdapter = new ProductTableAdapter(this, R.layout.item_product_table, resultInfoList);
            lv_product_table.setAdapter(productTableAdapter);
        } else {
            productTableAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void setNoMore() {
        lv_product_table.setNoMore();
    }

    @Override
    public void setMoreComplete() {
        lv_product_table.getMoreComplete();
    }

    @Override
    public void loadSucMenu(LoansTableMenu loansTableMenu) {

        productList.addAll(loansTableMenu.getProductList());
        LoansTableMenu.ProductListBean productListBean = new LoansTableMenu.ProductListBean();
        productListBean.setName("不限");
        productListBean.setCheck(true);
        productList.add(0, productListBean);

        workTypeList.addAll(loansTableMenu.getWorkTypeList());
        LoansTableMenu.WorkTypeListBean workTypeListBean = new LoansTableMenu.WorkTypeListBean();
        workTypeListBean.setName("不限");
        workTypeListBean.setCheck(true);
        workTypeList.add(0, workTypeListBean);

        LoansTableMenu.CreditCardBean creditCardBean = new LoansTableMenu.CreditCardBean();
        creditCardBean.setName("不限");
        creditCardBean.setCode("");
        creditCardBean.setCheck(true);
        creditCardBeanList.add(creditCardBean);
        creditCardBean = new LoansTableMenu.CreditCardBean();
        creditCardBean.setName("无信用卡");
        creditCardBean.setCode("0");
        creditCardBeanList.add(creditCardBean);
        creditCardBean = new LoansTableMenu.CreditCardBean();
        creditCardBean.setName("持有信用卡");
        creditCardBean.setCode("1");
        creditCardBeanList.add(creditCardBean);


        if (!isFirstLoad) {
            showPop(ll_toolbar);
        }
        isFirstLoad = false;

    }

    @Override
    public void loadFaiMenu(String errorMsg) {

    }

    @Override
    public void loadSucTableBuy(TabledBuy tabledBuy, String buyType) {
        if (StringUtil.isNotEmpty(buyType)) {//检验
            dialog = new CustomDialog(this, R.style.Customdialog, "提示", "是否确定购买？\n所需积分：" + tabledBuy.getScore() + " 积分"
                    , new CustomDialog.ButtonListener() {
                @Override
                public void left() {
                    dialog.dismiss();
                }

                @Override
                public void right() {
                    productTablePresenter.getApplyLoansBuyy(PreUtils.getUser(ProductTableActivity.this).getSalesID() + ""
                            , applyLoansID + "", applyLoansSN, ""
                            , "");

                    dialog.dismiss();
                }
            }, getString(R.string.cancel), getString(R.string.determine));
            dialog.show();
        } else {//购买
            setScreenAction("购买", "贷款-产品申请表-购买");
            ToastUtil.showShort("购买成功！可在\"已购买客户\"中管理 ");
            resultInfoList.remove(mPosition);
            productTableAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void loadFaiTableBuy(String errorMsg) {
        if (errorMsg.equals("您的剩余积分不够,请充值!")) {
            dialog = new CustomDialog(this, R.style.Customdialog, "提示", errorMsg
                    , new CustomDialog.ButtonListener() {
                @Override
                public void left() {
                    dialog.dismiss();
                }

                @Override
                public void right() {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("CompanyID", CompanyID);
                    map.put("CompanyTypeID", CompanyTypeID);
                    ActivitySkipUtil.skipAnotherActivity(ProductTableActivity.this, MineScoreActivity.class, map);
                    dialog.dismiss();
                }
            }, getString(R.string.cancel), getString(R.string.determine));
            dialog.show();
        }
    }
}
